package com.huluobo.a2203parkdemo.notice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import com.google.gson.Gson
import com.huluobo.a2203parkdemo.R
import com.huluobo.a2203parkdemo.adapter.NoticeAdapter
import com.huluobo.a2203parkdemo.databinding.ActivityNoticeBinding
import com.huluobo.base.bean.NoticeBean
import com.huluobo.base.mvvm.BaseActivity
import com.huluobo.base.net.Const
import dagger.hilt.android.AndroidEntryPoint
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody

@AndroidEntryPoint
class NoticeActivity : BaseActivity<ActivityNoticeBinding, NoticeViewModel>() {
    private lateinit var noticeAdapter: NoticeAdapter
    private var page = 0
    override fun initData() {
        val map = mutableMapOf<String, Int>()
        map[Const.PARAM_PAGE] = page
        val json = Gson().toJson(map)
        val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
        viewModel.getAllNotice(body)

        viewModel.getAllNoticeSuccess.observe(this) {
            val list = Gson().fromJson(it, NoticeBean::class.java)
            noticeAdapter.data.clear()
            noticeAdapter.data.addAll(list)
            noticeAdapter.notifyDataSetChanged()
        }
    }

    override fun initView() {
        binding.noticeRv.layoutManager = LinearLayoutManager(this)
        noticeAdapter = NoticeAdapter()
        binding.noticeRv.adapter = noticeAdapter

        binding.noticeHeader.headerTitle.text = "公告"
        binding.noticeHeader.headerBack.setOnClickListener { finish() }

        binding.noticePageTv.text = "第${page + 1}页"

        binding.noticePrePage.setOnClickListener {
            if (page != 0) {
                val map = mutableMapOf<String, Int>()
                page--
                map[Const.PARAM_PAGE] = page
                val json = Gson().toJson(map)
                val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
                viewModel.getAllNotice(body)
                binding.noticePageTv.text = "第${page + 1}页"
            } else {
                ToastUtils.showLong("已经是第一页了")
            }
        }

        binding.noticePostPage.setOnClickListener {
            val map = mutableMapOf<String, Int>()
            page++
            map[Const.PARAM_PAGE] = page
            val json = Gson().toJson(map)
            val body = RequestBody.create(Const.MEDIA_TYPE.toMediaTypeOrNull(), json)
            viewModel.getAllNotice(body)
            binding.noticePageTv.text = "第${page + 1}页"
        }
    }
}